package com.fantabest.common.client.widget;

import java.util.List;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.data.BaseTreeLoader;
import com.extjs.gxt.ui.client.data.BaseTreeModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.TreeLoader;
import com.extjs.gxt.ui.client.data.TreeModelReader;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.fantabest.common.client.FantaBestConstants;
import com.fantabest.common.client.RegistryKeys;
import com.fantabest.common.client.model.MenuChildData;

public class BaseMenu extends ContentPanel {

	protected FantaBestConstants constants = Registry.get(RegistryKeys.CONSTANTS);
	protected TreePanel<ModelData> treePanel;
	protected BaseTreeModel treeModel;
	protected TreeLoader<ModelData> treeLoader;
	
	public BaseMenu() {
		initUI();
	}

	private void initUI() {
		this.setLayout(new FitLayout());
		this.setHeading(constants.manage());
		this.setIcon(IconHelper.createStyle("management32",32,32));
		this.setBodyBorder(false);

		treeLoader = new BaseTreeLoader<ModelData>(  
		        new TreeModelReader<List<ModelData>>());
		
		TreeStore<ModelData> store = new TreeStore<ModelData>(treeLoader);

		treePanel = new TreePanel<ModelData>(store);
		treePanel.setAutoLoad(true);
		treePanel.setDisplayProperty("name");
		treePanel.setWidth(250);
		treePanel.setExpanded(treeModel, true);
		treePanel.setDeferHeight(true);
		
		treePanel.addListener(Events.OnClick, new Listener<BaseEvent>() {

			public void handleEvent(BaseEvent be) {
				TreePanel<ModelData> tree = (TreePanel<ModelData>)be.getSource();
				MenuChildData node = (MenuChildData)tree.getSelectionModel().getSelectedItem();
				Dispatcher.get().dispatch(node.getEventToDispatch());
			}
		});
		
		
		StoreFilterField<ModelData> filter = new StoreFilterField<ModelData>() {

			@Override
			protected boolean doSelect(Store<ModelData> store,
					ModelData parent, ModelData record, String property,
					String filter) {
				String name = record.get("name");
				name = name.toLowerCase();
				if (name.contains(filter.toLowerCase())) {
					return true;
				}
				return false;
			}

		};
		filter.bind(store);

		add(filter);
		add(treePanel);

	}
}
